#!/usr/bin/env python
"""Logging function specific to RyCE.
"""
__author__   = 'Don B. Stringham'
__version__  = '0.01'
__date__     = '12/23/2005 10:53:00 PM'
#-IMPORTS----------------------------------------------------------------------
import os
import time
import logging
import getpass
import conf
import cmdline
#-CONSTANTS--------------------------------------------------------------------
DEFAULT_LOG_NAME = 'ryce.log'
DEFAULT_LOG_DIR  = '/var/log/ryce'
USER_LOG_DIR = conf.USER_DIR + 'log' + os.sep
DEFAULT_FORMAT = '%(asctime)s; %(levelname)-8s; %(name)-10s; #%(lineno)-3d; %(message)s'
ENV_SUDO = 'SUDO_USER'
CMD_TYPE = 1
cur_time = time.localtime()
#-FUNCTIONS--------------------------------------------------------------------
def _get_real_user():
    """When run under sudo, the original user name is saved in the
    SUDO_USER environment variable.
    """
    user = None
    if os.environ.has_key(ENV_SUDO):
        user = os.environ[ENV_SUDO]
    else:
        user = getpass.getuser()
    return user

def _append_time(p_logDir):
    username = _get_real_user()
    p_logDir += '%s%4d-%02d-%02d'%(os.sep,
                                   cur_time[0], #year
                                   cur_time[1], #month
                                   cur_time[2]) #day
    p_logDir += '%s%s_%s_%s_%s%s'%(os.sep,
                                   cur_time[3], #hour
                                   cur_time[4], #minute
                                   cur_time[5], #second
                                   username,
                                   os.sep)
    return p_logDir

def _make_log_filename(p_logType = 0, p_logId = 0, p_prefix = ''):
    """Creates a unique file name based on the username and local time
    stamp.
    """
    global cur_time
    #TODO: Put in dynamic command-line log dir
    logDir = _append_time(DEFAULT_LOG_DIR)
    if not os.path.isdir(logDir):
        try:
            os.makedirs(logDir)
        except:
            logDir = _append_time(USER_LOG_DIR)
            try:
                os.makedirs(logDir)
            except:
                pass
    if p_logType == 1:
        logName = '%d_%s.log'%(p_logId, p_prefix)
    else:
        logName = DEFAULT_LOG_NAME
    return logDir+logName

def setup(verbose=False):
    logging.basicConfig(level=logging.DEBUG,
                        format=DEFAULT_FORMAT,
                        datefmt='%m-%d %H:%M',
                        filename=_make_log_filename(),
                        filemode='w')
    console = logging.StreamHandler()
    if verbose:
        console.setLevel(logging.DEBUG)
    else:
        console.setLevel(logging.INFO)
    formatter = logging.Formatter(DEFAULT_FORMAT)
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
